package com.tbm.impl.json;

import com.tbm.base.controller.BaseController;
import com.tbm.base.service.CommonService;
import com.tbm.base.service.JsonService;
import com.tbm.common.constant.EntityPathConstant;
import com.tbm.common.enums.RestfulEntity;
import com.tbm.common.util.PageData;
import com.tbm.common.util.SpringUtil;
import com.tbm.common.util.ToolUtil;
import com.tbm.entity.JsonEntity;
import com.tbm.entity.SystemUser;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by Administrator on 2017/9/13.
 */
@RestController
public class CommonControllerJson extends BaseController {

    @Autowired
    private JsonService jsonService;
    @Autowired
    private CommonService commonService;

    /**
     * Rest风格，此方法来返回所有的Table list
     * 约定优于配置
     * {path}---entity
     * {params}---参数
     * @return
     */
    @RequestMapping("/list/{path}/{params}")
    public Map<String,Object> jsonListRest(@PathVariable("path") String path,@PathVariable("params") String params){
        PageData pageData = this.getPageData();

        //table刷新和分页
        int startCurr = pageData.get("startCurr")==null?0:Integer.valueOf(pageData.get("startCurr").toString())-1;
        int length = pageData.get("length")==null?10:Integer.valueOf(pageData.get("length").toString());

        //搜索关键字
        String from = pageData.get("from")==null?"":pageData.get("from").toString();
        String to = pageData.get("to")==null?"":pageData.get("to").toString();
        String key = pageData.get("key")==null?"":pageData.get("key").toString();

        List<PageData> pageDataList = new ArrayList<PageData>();
        //获取排序的字段
        try {
            //创建Example样例
            Object bean = Class.forName(EntityPathConstant.ENTITYPATH+path).newInstance();
            Sort sort = new Sort(Sort.DEFAULT_DIRECTION.ASC,bean.toString());
            Pageable pageable = new PageRequest(startCurr,length,sort);
            String [] paramsString = params.split(",");
            if(!"".equals(key)){
                reflectParams(bean,paramsString[0],key);
            }
            if(!"".equals(from)){
                reflectParams(bean,paramsString[1],from);
            }
            if(!"".equals(to)){
                reflectParams(bean,paramsString[2],to);
            }

            Example ex = Example.of(bean);
            pageDataList = commonService.findAll(ex, pageable,bean.getClass());
        }  catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        //JSON列表
        Map<String ,Object> map = new HashMap<String, Object>();
        map.put("total",commonService.count(EntityPathConstant.REPOSITORYPATH+path+EntityPathConstant.REPOSITORYPATHFIX));
        map.put("rows", JSONArray.fromObject(pageDataList));
        return map;

    }

    private void reflectParams(Object bean,String param,String key){
        try {
            Method m = (Method)bean.getClass().getMethod(param,new Class[]{String.class});
            m.invoke(bean,key);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
